package com.sikadwafastdaisfondturbo.pretloan.ui.credit.activity

import android.view.View
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.databinding.CreditMainBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProActivity
import com.sikadwafastdaisfondturbo.pretloan.status.StatusRepository
import com.sikadwafastdaisfondturbo.pretloan.ui.credit.page.CreditCommonPage
import com.sikadwafastdaisfondturbo.pretloan.ui.credit.page.LimitPage
import com.sikadwafastdaisfondturbo.pretloan.ui.credit.page.RepayPage
import com.sikadwafastdaisfondturbo.pretloan.utils.config.Configs
import com.sikadwafastdaisfondturbo.pretloan.utils.helper.ForegroundBackgroundHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.helper.ForegroundBackgroundObserver
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls.addCommonParams
import com.sikadwafastdaisfondturbo.pretloan.utils.http.IHttpCallback
import com.sikadwafastdaisfondturbo.pretloan.utils.log.HHLog
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/21 19:28
 * @Annotation：贷款主页
 */
class CreditActivity: ProActivity() {
    lateinit var binding: CreditMainBinding

    //贷款额度
    private var mLimitPage: LimitPage? = null
    //贷款还款
    private var mRepayPage: RepayPage? = null
    //贷款 通用状态列表，包含：审核中、拒绝、放贷中、放贷中法语
    private var mCommonPage: CreditCommonPage? = null

    override fun getRootView(): View {
        binding = CreditMainBinding.inflate(layoutInflater)
        return binding.root
    }

    @Subscribe
    override fun initView() {
        setBackExit(true)
        setExitTips(getString(R.string.exit_tips))

        EventBus.getDefault().register(this)
        ForegroundBackgroundHelper.addObserve(onForegroundBackgroundObserver)
    }

    override fun initListener() {
    }

    override fun initData() {
        showLoading()
        loadProcessAction()
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    fun onRefreshProcess(event: String){
        when(event){
            Configs.Event.PROCESS_REFRESH -> {//刷新
                loadProcessAction()
            }
        }
    }

    /**
     * 显示贷款额度页面
     */
    fun showLimitPage(isComplete: Boolean){
        hideAllPage()
        if (mLimitPage == null) {
            mLimitPage = LimitPage(isComplete)
        }
        if (mLimitPage!!.isAdded) {
            showContainerFragement(mLimitPage)
            mLimitPage!!.isComplete = isComplete
            mLimitPage!!.showStateView()
        } else {
            addContainerFragement(R.id.containerLayout, mLimitPage)
        }
    }

    /**
     * 显示待还款页面
     */
    fun showRepayPage() {
        hideAllPage()
        if (mRepayPage == null) {
            mRepayPage = RepayPage()
        }
        if (mRepayPage!!.isAdded) {
            showContainerFragement(mRepayPage)
            mRepayPage!!.refreshAction()
        } else {
            addContainerFragement(R.id.containerLayout, mRepayPage)
        }
    }

    /**
     * 显示审核中、放款中、拒绝公用一个页面
     */
    fun showCommonPage(data: JSONObject) {
        hideAllPage()
        if (mCommonPage == null) {
            mCommonPage = CreditCommonPage(data)
        }
        if (mCommonPage!!.isAdded) {
            showContainerFragement(mCommonPage)
            mCommonPage!!.refreshView(data)
        } else {
            addContainerFragement(R.id.containerLayout, mCommonPage)
        }
    }

    /**
     * 隐藏所有的页面
     */
    private fun hideAllPage() {
        if (mLimitPage != null) {
            hideContainerFragement(mLimitPage)
        }
        if (mRepayPage != null) {
            hideContainerFragement(mRepayPage)
        }
        if (mCommonPage != null) {
            hideContainerFragement(mCommonPage)
        }
    }

    /**
     * 获取流程
     */
    private fun loadProcessAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.PROCESS)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                //保存用户流程状态
                if (obj != null) {
                    Configs.saveSPString(Configs.SPKEY.SIKADWA_PROCESS,obj.toString())
                    //通知全局流程刷新完成
                    EventBus.getDefault().post(Configs.Event.PROCESS_REFRESHED)
                }
                //1、判断是否存在 订单状态
                if (obj != null && obj.has("orderStatus")){
                    val orderStatus = obj.optString("orderStatus")
                    //待还款
                    if (StatusRepository(null,orderStatus).isRepayNow()){
                        showRepayPage()
                        return
                    }
                    //放款中
                    if (StatusRepository(null,orderStatus).isDisbursing()){
                        obj.put("eventRemark","CreditAudit Page")
                        showCommonPage(obj)
                        return
                    }
                    //申请贷款被拒绝
                    if (StatusRepository(null,orderStatus).isRejected()){
                        obj.put("eventRemark","CreditApplyFailed Page")
                        showCommonPage(obj)
                        return
                    }
                }

                //2、判断是否存在 贷款申请状态
                if (obj != null && obj.has("applyStatus")){
                    val applyStatus = obj.optString("applyStatus")
                    //审核中
                    if (StatusRepository(applyStatus).isReviewing()){
                        obj.put("eventRemark","CreditAudit Page")
                        showCommonPage(obj)
                        return
                    }
                    //被拒绝
                    if (StatusRepository(applyStatus).isRejected()){
                        obj.put("eventRemark","CreditApplyFailed Page")
                        showCommonPage(obj)
                        return
                    }
                }

                //3、直接显示贷款额度页面
                if (obj != null){
                    showLimitPage(obj.optJSONArray("steps")!!.length() == 0)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideLoading()
            }
        })
    }

    /**
     * 前后台切换监听
     */
    private val onForegroundBackgroundObserver = object : ForegroundBackgroundObserver {
        override fun foregroundBackgroundNotify(isForeground: Boolean) {
            HHLog.e("Main background>>>>>>>>>$isForeground")
            //从桌面进入前台，需要刷新总流程
//            if (isForeground) {
//                loadProcessAction()
//            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        ForegroundBackgroundHelper.removeObserver(onForegroundBackgroundObserver)
    }
}